﻿using System.Linq;
using System.Security.Claims;
using Identity;
using Identity.Searcher;
using JwtWebApi.Data;
using Microsoft.AspNetCore.Mvc.Filters;

namespace JwtWebApi.Filters
{
    public class PermissionFilter : ActionFilterAttribute
    {
        private readonly ApplicationDbContext _context;

        public PermissionFilter(ApplicationDbContext context)
        {
            _context = context;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);
            if (context.HttpContext.User == null || context.HttpContext.User.Identity == null) return;
            foreach (var input in context.ActionArguments.Values)
            {
                var searcher = input as PermissionSearcher;
                if (searcher != null)
                {
                    searcher.UserId = context.HttpContext.User.Claims
                        .FirstOrDefault(f => f.Type == ClaimTypes.NameIdentifier)?.Value;
                    searcher.Roles = _context.FindRolesByUserId(searcher.UserId);
                }
            }
        }
    }
}